//
//  This file is part of a reduced file concatenation of the CwlViews
//  framework with internal interfaces for source inclusion in projects instead
//  of library inclusion.
//  For details, visit: https://github.com/mattgallagher/CwlViews
//
//  Copyright © 2015-2018 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved.
//
//  Permission to use, copy, modify, and/or distribute this software for any
//  purpose with or without fee is hereby granted, provided that the above
//  copyright notice and this permission notice appear in all copies.
//
//  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
//  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
//  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
//  SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
//  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
//  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
//  IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
//  This file was generated by the CwlUtilsConcat tool on 2018-04-02 04:01:17 +0000 from the following files:
//
//    CwlArrayMutation.swift
//    CwlScopedValues.swift
//    CwlBindingName.swift
//    CwlStackMutation.swift
//    CwlStateContainer.swift
//    CwlBinder.swift
//    CwlTargetAction.swift
//    CwlBinderParameters.swift
//    CwlBinderState.swift
//    CwlSetMutation.swift
//    CwlBinderChain.swift
//    CwlFilteredAdapter.swift
//    CwlObjectStorage.swift
//    CwlArrayMutationUtilities.swift
//    CwlCoder.swift
//    CwlStateAdapter.swift
//    CwlBinderPreparer.swift
//    CwlDynamicValue.swift
//    CwlStackAdapter.swift
//    CwlConstructingBinder.swift
//

#if os(macOS)
	import AppKit
#else
	import UIKit
#endif

// MARK: ### CwlArrayMutation.swift ###

/// This enum is intended to be embedded in an ArrayMutation<Value>. The ArrayMutation<Value> combines an IndexSet with this enum. This enum specifies what actions should be taken at the locations specified by the IndexSet.
///
/// 
enum ArrayMutationKind {
	/// The values at the locations specified by the IndexSet should be deleted.
	/// NOTE: the IndexSet specifies the indexes *before* deletion (and must therefore be applied in reverse).
	case delete

	/// The associated Array<Value> contains values that should be inserted such that they have the indexes specified in IndexSet. The Array<Value> and IndexSet must have identical counts.
	/// NOTE: the IndexSet specifies the indexes *after* insertion (and must therefore be applied in forward order).
	case insert

	/// Values are deleted from one end and inserted onto the other. If `Int` is positive, values are deleted from the `startIndex` end and inserted at the `endIndex` end, if `Int` is negative, value are deleted from the `endIndex` end and inserted at the `startIndex`end.
	/// The magnitude of `Int` specifies the number of deleted rows and the sign specified the end.
	/// The Array<Value> contains values that should be inserted at the other end of the collection.
	/// The IndexSet contains the indexes of any revealed (scrolled into view) rows
	case scroll(Int)

	/// The associated Array<Value> contains updated values at locations specified by the IndexSet. Semantically, the item should be modelled as updated but not replaced. The Array<Value> and IndexSet must have identical counts.
	// In many cases, update and replace are the same. The only differences relate to scenarios where the items are considered to have "identity". An update *retains* the previous identity whereas a replace *discards* any previous identity.
	case update
	
	/// The values at the locations specified by the IndexSet should be removed from their locations and spliced back in at the location specified by the associated Int index. For scrolled subranges, items may not be moved from outside or to outside the visible range (items moved from outside the visible range must be inserted and items moved outside the visible range must be deleted)
	/// NOTE: the IndexSet specifies the indexes *before* removal (and must therefore be applied in reverse) and the Int index specifies an index *after* removal.
	case move(Int)

	/// Equivalent to a Deletion of all previous indexes and an Insertion of the new values. The associated Array<Value> contains the new state of the array. All previous values should be discarded and the entire array replaced with this new version. The Array<Value> and IndexSet must have identical counts.
	/// NOTE: the IndexSet specifies the indexes *after* insertion (and must therefore be applied in forward order).
	case reload
}

/// An `ArrayMutation` communicates changes to an array in one context so that another array, mirroring its contents in another context, can mimic the same changes.
/// Subscribing to a stream of `ArrayMutation`s is sufficient to communication the complete state and animatable transitions of an array between to parts of a program.
/// In most cases, the source and destination will need to keep their own complete copy of the array to correctly calculate the effect of the mutation.
struct ArrayMutation<Value>: ExpressibleByArrayLiteral {
	/// Determines the meaning of this `ArrayMutation`
	let kind: ArrayMutationKind

	/// The meaning of the indexSet is dependent on the `kind` – it may contain indexes in the array that will be deleted by this mutation or it may contain indexes that new entries will occupy after application of this mutation.
	let indexSet: IndexSet
	
	/// New values that will be inserted at locations determined by the `kind` and the `indexSet`.
	let values: Array<Value>
	
	/// Construct an empty array mutation that represents a no-op.
	init() {
		self.kind = .update
		self.indexSet = IndexSet()
		self.values = []
	}
	
	/// Construct from components.
	init<S>(indexSet: IndexSet, kind: ArrayMutationKind, values: S) where S: Sequence, S.Element == Value {
		self.kind = kind
		self.indexSet = indexSet
		self.values = Array(values)
	}
	
	/// Construct a mutation that represents the deletion of the values at a set of indices.
	init(deletedIndexSet: IndexSet) {
		self.kind = .delete
		self.indexSet = deletedIndexSet
		self.values = []
	}
	
	/// Construct a mutation that represents the deletion of a value at an index.
	init(deletedIndex: Int) {
		self.kind = .delete
		self.indexSet = IndexSet(integer: deletedIndex)
		self.values = []
	}
	
	/// Construct a mutation that represents the deletion of a value at an index.
	static func deleted(at index: Int) -> ArrayMutation<Value> {
		return ArrayMutation(deletedIndex: index)
	}
	
	/// Construct a mutation that represents the deletion of the values within a range indices.
	init(deletedRange: CountableRange<Int>) {
		self.kind = .delete
		self.indexSet = IndexSet(integersIn: deletedRange)
		self.values = []
	}
	
	/// Construct a mutation that represents the deletion of a value at an index.
	init<S>(scrollForwardRevealing indexSet: IndexSet, values: S) where S: Sequence, S.Element == Value {
		let array = Array(values)
		assert(indexSet.count == array.count)
		self.kind = .scroll(indexSet.count)
		self.indexSet = indexSet
		self.values = Array(array)
	}
	
	/// Construct a mutation that represents the deletion of a value at an index.
	init<S>(scrollBackwardRevealing indexSet: IndexSet, values: S) where S: Sequence, S.Element == Value {
		let array = Array(values)
		assert(indexSet.count == array.count)
		self.kind = .scroll(-indexSet.count)
		self.indexSet = indexSet
		self.values = array
	}
	
	/// Construct a mutation that represents the insertion of a number of values at a set of indices. The count of indices must match the count of values.
	init<S>(insertedIndexSet: IndexSet, values: S) where S: Sequence, S.Element == Value {
		let array = Array(values)
		assert(insertedIndexSet.count == array.count)
		self.kind = .insert
		self.indexSet = insertedIndexSet
		self.values = array
	}
	
	/// Construct a mutation that represents the insertion of a value at an index.
	init(insertedIndex: Int, value: Value) {
		self.kind = .insert
		self.indexSet = IndexSet(integer: insertedIndex)
		self.values = [value]
	}

	/// Construct a mutation that represents the insertion of a number of values within a range of indices. The count of the range must match the count of values.
	init<S>(insertedRange: CountableRange<Int>, values: S) where S: Sequence, S.Element == Value {
		let array = Array(values)
		assert(insertedRange.count == array.count)
		self.kind = .insert
		self.indexSet = IndexSet(integersIn: insertedRange)
		self.values = array
	}
	
	/// Construct a mutation that discards any previous history and simply starts with a completely new array.
	init<S>(reload values: S) where S: Sequence, S.Element == Value {
		let array = Array(values)
		self.kind = .reload
		self.indexSet = IndexSet(integersIn: array.indices)
		self.values = array
	}
	
	/// A .Reload mutation can be constructed from an array literal (since it is equivalent to an array assignment).
	init(arrayLiteral elements: Value...) {
		self.init(reload: elements)
	}
	
	/// Construct a mutation that represents the update of a number of values at a set of indices. The count of indices must match the count of values.
	init<S>(updatedIndexSet: IndexSet, values: S) where S: Sequence, S.Element == Value {
		let array = Array(values)
		assert(updatedIndexSet.count == array.count)
		self.kind = .update
		self.indexSet = updatedIndexSet
		self.values = array
	}
	
	/// Construct a mutation that represents the update of a value at an index.
	init(updatedIndex: Int, value: Value) {
		self.kind = .update
		self.indexSet = IndexSet(integer: updatedIndex)
		self.values = [value]
	}
	
	/// Construct a mutation that represents the udpate of a number of values within a range of indices. The count of the range must match the count of values.
	init<S>(updatedRange: CountableRange<Int>, values: S) where S: Sequence, S.Element == Value {
		let array = Array(values)
		assert(updatedRange.count == array.count)
		self.kind = .update
		self.indexSet = IndexSet(integersIn: updatedRange)
		self.values = array
	}
	
	/// Construct a mutation that represents the move of a number of values from a set of indices to a new range starting at targetIndex. NOTE: the order of values once inserted at targetIndex must be the same as the order in movedIndexSet.
	init(movedIndexSet: IndexSet, targetIndex: Int) {
		self.kind = .move(targetIndex)
		self.indexSet = movedIndexSet
		self.values = []
	}

	/// Construct a mutation that represents the move of a value at movedIndex to a new range starting at targetIndex.
	init(movedIndex: Int, targetIndex: Int) {
		self.kind = .move(targetIndex)
		self.indexSet = IndexSet(integer: movedIndex)
		self.values = []
	}

	/// Construct a mutation that represents the move of a range of values to a new range starting at targetIndex. NOTE: the order of values once inserted at targetIndex must be the same as the order in movedRange.
	init(movedRange: CountableRange<Int>, targetIndex: Int) {
		self.kind = .move(targetIndex)
		self.indexSet = IndexSet(integersIn: movedRange)
		self.values = []
	}

	/// Apply the mutation described by this value to the provided array
	func apply<C: RangeReplaceableCollection>(to a: inout C) where C.Index == Int, C.Iterator.Element == Value {
		switch kind {
		case .delete:
			indexSet.rangeView.reversed().forEach { a.removeSubrange($0) }
		case .scroll(let offset):
			a.removeSubrange(offset > 0 ? a.startIndex..<offset : (a.endIndex + offset)..<a.endIndex)
			a.insert(contentsOf: values, at: offset > 0 ? a.endIndex : a.startIndex)
		case .move(let index):
			let moving = indexSet.map { a[$0] }
			indexSet.rangeView.reversed().forEach { a.removeSubrange($0) }
			a.insert(contentsOf: moving, at: index)
		case .insert:
			for (i, v) in zip(indexSet, values) {
				a.insert(v, at: i)
			}
		case .update:
			for (i, v) in zip(indexSet, values) {
				a.insert(v, at: i)
			}
		case .reload:
			a.replaceSubrange(a.startIndex..<a.endIndex, with: values)
		}
	}
	
	func map<Other>(_ transform: (Value) -> Other) -> ArrayMutation<Other> {
		return ArrayMutation<Other>(indexSet: indexSet, kind: kind, values: values.map(transform))
	}
	
	func removed(previousIndices a: CountableRange<Int>) -> IndexSet {
		switch kind {
		case .delete: return indexSet
		case .scroll(let offset): return IndexSet(integersIn: offset > 0 ? (a.endIndex - offset)..<a.endIndex : a.startIndex..<(a.startIndex + offset))
		case .reload: return IndexSet(integersIn: a)
		case .move: fallthrough
		case .insert: fallthrough
		case .update: return IndexSet()
		}
	}
	
	func inserted(subsequentIndices a: CountableRange<Int>) -> IndexSet {
		switch kind {
		case .insert: return indexSet
		case .scroll(let offset): return IndexSet(integersIn: offset > 0 ? a.startIndex..<offset : (a.endIndex + offset)..<a.endIndex)
		case .reload: return IndexSet(integersIn: a)
		case .delete: return indexSet
		case .move: fallthrough
		case .update: return IndexSet()
		}
	}
	
	/// Updates a row count due to this mutation.
	func delta(_ rowCount: inout Int) {
		switch kind {
		case .reload: rowCount = values.count
		case .delete: rowCount -= indexSet.count
		case .scroll(let offset): rowCount += values.count - (offset > 0 ? offset : -offset)
		case .insert: rowCount += values.count
		case .move: return
		case .update: return
		}
	}
}

// MARK: ### CwlScopedValues.swift ###

import Foundation

struct ScopedValues<Scope, Value>: ExpressibleByArrayLiteral {
	typealias ArrayLiteralElement = ScopedValues<Scope, Value>
	init(arrayLiteral elements: ScopedValues<Scope, Value>...) {
		self.pairs = elements.flatMap { $0.pairs }
	}
	
	let pairs: [(scope: Scope, value: Value)]
	init(pairs: (Scope, Value)...) {
		self.pairs = pairs
	}
	init(pairs: [(Scope, Value)]) {
		self.pairs = pairs
	}
	init(scope: Scope, value: Value) {
		self.pairs = [(scope, value)]
	}
	static func value(_ value: Value, for scope: Scope) -> ScopedValues<Scope, Value> {
		return ScopedValues(scope: scope, value: value)
	}
}

// MARK: ### CwlBindingName.swift ###

infix operator --: AssignmentPrecedence
infix operator <--: AssignmentPrecedence
infix operator -->: AssignmentPrecedence

struct BindingName<Value, Binding> {
	var constructor: (Value) -> Binding
	init(_ constructor: @escaping (Value) -> Binding) {
		self.constructor = constructor
	}

	/// Build a signal binding (invocations on the instance after construction) from a name and a signal
	///
	/// - Parameters:
	///   - name: the binding name
	///   - value: the binding argument
	/// - Returns: the binding
	static func <--<Interface: SignalInterface>(name: BindingName<Value, Binding>, value: Interface) -> Binding where Signal<Interface.OutputValue> == Value {
		return name.constructor(value.signal)
	}

	/// Build a value binding (property changes on the instance) from a name and a signal (values over time)
	///
	/// - Parameters:
	///   - name: the binding name
	///   - value: the binding argument
	/// - Returns: the binding
	static func <--<Interface: SignalInterface>(name: BindingName<Value, Binding>, value: Interface) -> Binding where DynamicValue<Interface.OutputValue> == Value {
		return name.constructor(DynamicValue<Interface.OutputValue>.fromDynamic(value.signal))
	}

	/// Build an action binding (callbacks triggered by the instance) from a name and a signal input.
	///
	/// - Parameters:
	///   - name: the binding name
	///   - value: the binding argument
	/// - Returns: the binding
	static func --><InputInterface: SignalInputInterface>(name: BindingName<Value, Binding>, value: InputInterface) -> Binding where SignalInput<InputInterface.InputValue> == Value {
		return name.constructor(value.input)
	}

	/// Build an `TargetAction` binding (callbacks triggered by the instance) from a name and a signal input.
	///
	/// - Parameters:
	///   - name: the binding name
	///   - value: the binding argument
	/// - Returns: the binding
	static func --><InputInterface: SignalInputInterface>(name: BindingName<Value, Binding>, value: InputInterface) -> Binding where TargetAction<InputInterface.InputValue> == Value {
		return name.constructor(.singleTarget(value.input))
	}
	
	/// Build a static binding (construction-only property) from a name and a constant value
	///
	/// - Parameters:
	///   - name: the binding name
	///   - value: the binding argument
	/// - Returns: the binding
	static func --<A>(name: BindingName<Value, Binding>, value: A) -> Binding where Value == StaticValue<A> {
		return name.constructor(Value.fromConstant(value))
	}

	/// Build a value binding (property changes on the instance) from a name and a constant value
	///
	/// - Parameters:
	///   - name: the binding name
	///   - value: the binding argument
	/// - Returns: the binding
	static func --<A>(name: BindingName<Value, Binding>, value: A) -> Binding where DynamicValue<A> == Value {
		return name.constructor(DynamicValue<A>.fromConstant(value))
	}

	/// Build a delegate binding (synchronous callback) from a name and function with no parameters
	///
	/// - Parameters:
	///   - name: the binding name
	///   - value: the binding argument
	/// - Returns: the binding
	static func --<R>(name: BindingName<Value, Binding>, value: @escaping () -> R) -> Binding where Value == () -> R {
		return name.constructor(value)
	}

	/// Build a delegate binding (synchronous callback) from a name and function with one parameter
	///
	/// - Parameters:
	///   - name: the binding name
	///   - value: the binding argument
	/// - Returns: the binding
	static func --<A, R>(name: BindingName<Value, Binding>, value: @escaping (A) -> R) -> Binding where Value == (A) -> R {
		return name.constructor(value)
	}

	/// Build a delegate binding (synchronous callback) from a name and function with two parameters
	///
	/// - Parameters:
	///   - name: the binding name
	///   - value: the binding argument
	/// - Returns: the binding
	static func --<A, B, R>(name: BindingName<Value, Binding>, value: @escaping (A, B) -> R) -> Binding where Value == (A, B) -> R {
		return name.constructor(value)
	}

	/// Build a delegate binding (synchronous callback) from a name and function with three parameters
	///
	/// - Parameters:
	///   - name: the binding name
	///   - value: the binding argument
	/// - Returns: the binding
	static func --<A, B, C, R>(name: BindingName<Value, Binding>, value: @escaping (A, B, C) -> R) -> Binding where Value == (A, B, C) -> R {
		return name.constructor(value)
	}

	/// Build a delegate binding (synchronous callback) from a name and function with four parameters
	///
	/// - Parameters:
	///   - name: the binding name
	///   - value: the binding argument
	/// - Returns: the binding
	static func --<A, B, C, D, R>(name: BindingName<Value, Binding>, value: @escaping (A, B, C, D) -> R) -> Binding where Value == (A, B, C, D) -> R {
		return name.constructor(value)
	}

	/// Build a delegate binding (synchronous callback) from a name and function with five parameters
	///
	/// - Parameters:
	///   - name: the binding name
	///   - value: the binding argument
	/// - Returns: the binding
	static func --<A, B, C, D, E, R>(name: BindingName<Value, Binding>, value: @escaping (A, B, C, D, E) -> R) -> Binding where Value == (A, B, C, D, E) -> R {
		return name.constructor(value)
	}
}

#if os(macOS)
extension BindingName {
	/// Build a first-responder `TargetAction` binding (callbacks triggered by the instance) from a name and a selector.
	///
	/// - Parameters:
	///   - name: the binding name
	///   - value: the binding argument
	/// - Returns: the binding
	static func --><A>(name: BindingName<TargetAction<A>, Binding>, value: Selector) -> Binding where Value == TargetAction<A> {
		return name.constructor(Value.fromSelector(value))
	}
}
#endif

// MARK: ### CwlStackMutation.swift ###

enum StackMutation<Value>: ExpressibleByArrayLiteral {
	init(arrayLiteral elements: Value...) {
		self = .reload(elements)
	}
	
	typealias ArrayLiteralElement = Value
	
	case push(Value)
	case pop
	case popToCount(Int)
	case reload([Value])
	
	func apply(to stack: inout Array<Value>) {
		switch self {
		case .push(let v): stack.append(v)
		case .pop: stack.removeLast()
		case .popToCount(let c): stack.removeLast(stack.count - c)
		case .reload(let newStack): stack = newStack
		}
	}
}

extension SignalInterface {
	func stackMap<A, B>(_ transform: @escaping (A) -> B) -> Signal<StackMutation<B>> where OutputValue == StackMutation<A> {
		return map { m in
			switch m {
				case .push(let a): return StackMutation<B>.push(transform(a))
				case .pop: return StackMutation<B>.pop
				case .popToCount(let i): return StackMutation<B>.popToCount(i)
				case .reload(let array): return StackMutation<B>.reload(array.map { transform($0) })
			}
		}
	}
}

// MARK: ### CwlStateContainer.swift ###

protocol StateContainer: Cancellable, Codable {
	var persistentValueChanged: Signal<()> { get }
	var childValues: [StateContainer] { get }
}

extension StateContainer {
	var childValues: [StateContainer] { return [] }
	var persistentValueChanged: Signal<()> {
		return Signal<()>.merge(childValues.map {
			return $0.persistentValueChanged
		})
	}
	func cancel() {
		childValues.forEach { $0.cancel() }
	}
}

#if swift(>=4.1)
	extension Array: Cancellable where Element: Cancellable {
		mutating func cancel() {
			for var v in self {
				v.cancel()
			}
		}
	}

	extension Array: StateContainer where Element: StateContainer {
		var childValues: [StateContainer] {
			return self.map { $0 as StateContainer }
		}
	}

	extension Optional: StateContainer where Wrapped: StateContainer {
		var childValues: [StateContainer] {
			guard let s = self else { return [] }
			return [s]
		}
	}
#else
	extension Array: StateContainer {
		var childValues: [StateContainer] {
			if let f = first, !(f is StateContainer) {
				return []
			}
			return self.flatMap { $0 as? StateContainer }
		}
	}

	extension Optional: StateContainer {
		var childValues: [StateContainer] {
			if let s = self, let sc = s as? StateContainer {
				return [sc]
			}
			return []
		}
	}
#endif

// MARK: ### CwlBinder.swift ###

/// This protocol is the minimum definition for a "binder". A binder takes a list of properties and behaviors (called bindings) and constructs an object with the properties and conforming to the behaviors.
protocol Binder: BinderChain where Preparer: DerivedPreparer, Storage: BinderStorage, Inherited: BinderChain {
	associatedtype Parameters: BinderParameters where Parameters.Binding == Binding
	associatedtype Output
	var state: BinderState<Output, Parameters> { get set }
	
	static func bindingToInherited(_ binding: Binding) -> Inherited.Binding?
	func applyBindings(to instance: Instance)
	func consumeBindings() -> [Binding]
	init(state: BinderState<Output, Parameters>)
}

extension Binder where Parameters == BindingsOnlyParameters<Binding> {
	/// A constructor used when dynamically assembling arrays of bindings
	///
	/// - Parameters:
	///   - bindings: array of bindings
	init(bindings: [Binding]) {
		self.init(state: .pending(BindingsOnlyParameters(bindings: bindings)))
	}

	/// A constructor for a binder.
	///
	/// - Parameters:
	///   - bindings: list of bindings
	init(_ bindings: Binding...) {
		self.init(state: .pending(BindingsOnlyParameters(bindings: bindings)))
	}
}

extension Binder where Parameters == BinderSubclassParameters<Instance, Binding> {
	/// A constructor used when dynamically assembling arrays of bindings. Takes an optional subclass for the constructed instance.
	///
	/// - Parameters:
	///   - subclass: runtime subclass of the instance
	///   - bindings: array of bindings
	init(subclass: Instance.Type = Instance.self, bindings: [Binding]) {
		let params = BinderSubclassParameters<Instance, Binding>(subclass: subclass, bindings: bindings)
		self.init(state: .pending(params))
	}
	
	/// The preferred constructor for binders. Takes an optional subclass for the constructed instance and a list of bindings as a variable argument list.
	///
	/// - Parameters:
	///   - subclass: runtime subclass of the instance
	///   - bindings: list of bindings
	init(subclass: Instance.Type = Instance.self, _ bindings: Binding...) {
		let params = BinderSubclassParameters<Instance, Binding>(subclass: subclass, bindings: bindings)
		self.init(state: .pending(params))
	}
}

extension Binder {
	/// Invokes `consume` on the underlying state. If the state is not `pending`, this will trigger a fatal error. State will be set to `consumed`.
	///
	/// - Returns: the array of `Binding` from the state parameters.
	func consumeBindings() -> [Binding] {
		return state.consume().bindings
	}

	/// A utility function that can be called from ConstructingBinder.instance or other functions to turn parameters from a BinderState into a Binder.Output using the Binder.Preparer. The default invocation in ConstructingBinder.instance is normally used unless special construction requirements are involved.
	///
	/// - Parameters:
	///   - additional: ad hoc bindings, applied after other bindings
	///   - storageConstructor: function to construct an empty BinderStorage, usually Preparer.constructStorage()
	///   - instanceConstructor: function to construct an unconfigured instance, usually Preparer.constructInstance(subclass:)
	///   - combine: function to link the instance, storage and generated Cancellables
	///   - output: chooses the instance or storage to return as the primary output
	/// - Returns: the output
	func binderConstruct(
		additional: ((Instance) -> Cancellable?)?,
		storageConstructor: (Preparer, Parameters, Instance) -> Storage,
		instanceConstructor: (Preparer, Parameters) -> Instance,
		combine: (Instance, Storage, [Cancellable]) -> (),
		output: (Instance, Storage) -> Output) -> Output {
		return state.construct { parameters in
			var preparer = Preparer.init()
			preparer.prepareBindings(parameters.bindings)
			let instance = instanceConstructor(preparer, parameters)
			let storage = storageConstructor(preparer, parameters, instance)
			preparer.applyBindings(parameters.bindings, instance: instance, storage: storage, additional: additional, combine: combine)
			return output(instance, storage)
		}
	}

	/// A utility function that can be called from Binder.applyBindings(to:) or other functions to turn parameters from a BinderState into a Binder.Output using the Binder.Preparer. The default implementation of Binder.applyBindings(to:) is normally used unless special construction requirements are involved.
	///
	/// - Parameters:
	///	- instance: the instance to which bindings should be applied
	///   - additional: ad hoc bindings, applied after other bindings
	///   - storageConstructor: function to construct an empty BinderStorage, usually Preparer.constructStorage()
	///   - combine: function to link the instance, storage and generated Cancellables
	/// - Returns: the output
	func binderApply(to instance: Instance,
		additional: ((Instance) -> Cancellable?)?,
		storageConstructor: (Preparer, Parameters, Instance) -> Storage,
		combine: (Instance, Storage, [Cancellable]) -> ()) {
		state.apply(instance: instance) { inst, parameters in
			var preparer = Preparer.init()
			preparer.prepareBindings(parameters.bindings)
			let storage = storageConstructor(preparer, parameters, instance)
			preparer.applyBindings(parameters.bindings, instance: instance, storage: storage, additional: additional, combine: combine)
		}
	}
}

extension Binder where Preparer: StoragePreparer, Instance: NSObject, Output == Instance {
	/// A default implementation of `applyBindings` for the common case.
	///
	/// - Parameter instance: the instance to which bindings should be applied
	func applyBindings(to instance: Instance) {
		binderApply(to: instance, additional: nil, storageConstructor: { prep, params, i in prep.constructStorage() }, combine: embedStorageIfInUse)
	}
}

// MARK: ### CwlTargetAction.swift ###

/// This type encapsulates the idea that target-action pairs in Cocoa may target a specific object (by setting the target to non-nil) or may let the responder chain search for a responder that handles a specific selector.
enum TargetAction<Value> {
	typealias ValueType = Value
	case firstResponder(Selector)
	case singleTarget(SignalInput<Value>)
	static func fromSelector(_ selector: Selector) -> TargetAction<Value> {
		return .firstResponder(selector)
	}
	static func fromSingleTarget(_ input: SignalInput<ValueType>) -> TargetAction<Value> {
		return .singleTarget(input)
	}
}

protocol TargetActionSender: class {
	var action: Selector? { get set }
	var target: AnyObject? { get set }
}

extension TargetAction {
	func apply<U: TargetActionSender>(instance: U, constructTarget: () -> SignalActionTarget, processor: @escaping (Any?) -> Value) -> Cancellable? {
		switch self {
		case .firstResponder(let s):
			instance.target = nil
			instance.action = s
			return nil
		case .singleTarget(let s):
			let target = constructTarget()
			instance.target = target
			instance.action = target.selector
			return target.signal.map(processor).cancellableBind(to: s)
		}
	}
}

// MARK: ### CwlBinderParameters.swift ###

/// The mandatory requirement of BinderParameters is that they include an array of bindings
protocol BinderParameters {
	associatedtype Binding
	var bindings: [Binding] { get }
}

/// A minimalist implementation of `BinderParameters`
struct BindingsOnlyParameters<Binding>: BinderParameters {
	let bindings: [Binding]
	init(bindings: [Binding]) {
		self.bindings = bindings
	}
}

struct BinderSubclassParameters<Instance, Binding>: BinderParameters {
	let subclass: Instance.Type
	let bindings: [Binding]
	init(subclass: Instance.Type, bindings: [Binding]) {
		self.subclass = subclass
		self.bindings = bindings
	}
}

struct BinderAdditionalParameters<Instance, Binding, Additional>: BinderParameters {
	let subclass: Instance.Type
	let additional: Additional
	let bindings: [Binding]
	init(subclass: Instance.Type, additional: Additional, bindings: [Binding]) {
		self.subclass = subclass
		self.additional = additional
		self.bindings = bindings
	}
}


// MARK: ### CwlBinderState.swift ###

/// A binder exists in one of three states, a pre-constructed state, a constructed state (with the constructed output cached) and a consumed state (bindings applied to another instance or removed for testing purposes).
///
/// - constructed: the output object was constructed and remains cached as long as the state is retained
/// - pending: the set of parameters for construction 
/// - consumed: this object is no longer valid
enum BinderState<Output, Parameters: BinderParameters> {
	case constructed(Output)
	case pending(Parameters)
	case consumed

	/// If the state is not `pending`, this will trigger a fatal error. State will be set to `consumed`.
	///
	/// - Returns: the parameters of the `pending` state. State will be set to `consumed`.
	mutating func consume() -> Parameters {
		switch self {
		case .pending(let p): return p
		default: fatalError("Attempt to consume already consumed bindings")
		}
	}
	
	/// If the state is `consumed`, this will trigger a fatal error. If the state is `constructed`, this will return the already constructed output. Otherwise, the `generate` closure will be run to get a new `Output` and the state will be set to `constructed`.
	///
	/// - Parameters:
	///   - generate: a function that can create an `Output` with properties and behaviors from `Parameters`.
	/// - Returns: the parameters of the `pending` state
	mutating func construct(generate: (Parameters) -> Output) -> Output {
		switch self {
		case .constructed(let i): return i
		case .pending(let p):
			self = .consumed
			let instance = generate(p)
			self = .constructed(instance)
			return instance
		default: fatalError("Attempt to apply already consumed bindings")
		}
	}

	/// If the state is not `pending`, this will trigger a fatal error. State will be set to `consumed`.
	///
	/// NOTE: this function is generic over `Instance`. The `Instance` and `Output` types are usually but not necessarily the same (e.g. when you're configuring an internal instance but you hold the instance using a separate output wrapper).
	///
	/// - Parameters:
	///   - instance: an existing `Instance` that will receive properties and behaviors from the `Parameters`
	///   - handle: a function that can configure `Instance` with properties and behaviors from `Parameters`.
	mutating func apply<Instance>(instance: Instance, handle: (Instance, Parameters) -> ()) {
		switch self {
		case .pending(let p):
			self = .consumed
			handle(instance, p)
		default: fatalError("Attempt to apply already consumed bindings")
		}
	}
}

typealias ConstructingBinderState<Instance, Binding> = BinderState<Instance, BinderSubclassParameters<Instance, Binding>>


// MARK: ### CwlSetMutation.swift ###

import Foundation

enum SetMutationKind {
	case delete
	case insert
	case update
	case reload
}

struct SetMutation<Element> {
	let kind: SetMutationKind
	let values: Array<Element>
	
	init(kind: SetMutationKind, values: Array<Element>) {
		self.kind = kind
		self.values = values
	}
	
	static func delete(_ values: Array<Element>) -> SetMutation<Element> {
		return SetMutation(kind: .delete, values: values)
	}
	
	static func insert(_ values: Array<Element>) -> SetMutation<Element> {
		return SetMutation(kind: .insert, values: values)
	}
	
	static func update(_ values: Array<Element>) -> SetMutation<Element> {
		return SetMutation(kind: .update, values: values)
	}
	
	static func reload(_ values: Array<Element>) -> SetMutation<Element> {
		return SetMutation(kind: .reload, values: values)
	}
	
	func apply(to array: inout Array<Element>, equate: @escaping (Element, Element) -> Bool, compare: @escaping (Element, Element) -> Bool) -> [ArrayMutation<Element>] {
		switch kind {
		case .delete:
			var sorted = values.sorted(by: compare)
			var oldIndices = IndexSet()
			var arrayIndex = 0
			var sortedIndex = 0
			while arrayIndex < array.count && sortedIndex < sorted.count {
				if !equate(array[arrayIndex], sorted[sortedIndex]) {
					arrayIndex += 1
				} else {
					oldIndices.insert(arrayIndex)
					sortedIndex += 1
					arrayIndex += 1
				}
			}
			precondition(sortedIndex == sorted.count, "Unable to find deleted items.")
			oldIndices.reversed().forEach { array.remove(at: $0) }
			return [ArrayMutation<Element>(deletedIndexSet: oldIndices)]
		case .insert:
			var sorted = values.sorted(by: compare)
			var newIndices = IndexSet()
			var arrayIndex = 0
			var sortedIndex = 0
			while arrayIndex < array.count && sortedIndex < sorted.count {
				if compare(array[arrayIndex], sorted[sortedIndex]) {
					arrayIndex += 1
				} else {
					newIndices.insert(arrayIndex)
					array.insert(sorted[sortedIndex], at: arrayIndex)
					sortedIndex += 1
					arrayIndex += 1
				}
			}
			while sortedIndex < sorted.count {
				newIndices.insert(arrayIndex)
				array.insert(sorted[sortedIndex], at: arrayIndex)
				sortedIndex += 1
				arrayIndex += 1
			}
			return [ArrayMutation<Element>(insertedIndexSet: newIndices, values: sorted)]
		case .update:
			// It would be nice if this was better than n squared complexity and aggregated the updates, rather than issueing updates for individual rows.
			var result = Array<ArrayMutation<Element>>()
			for v in values {
				let oldIndex = array.index { u in equate(v, u) }!
				array.remove(at: oldIndex)
				let newIndex = array.index { u in compare(v, u) } ?? array.count
				array.insert(v, at: newIndex)
				if newIndex == oldIndex {
					result.append(.updated(v, at: oldIndex))
				} else {
					// This ordering (moved, then updated) is required to make UITableView animations work correctly.
					result.append(.moved(from: oldIndex, to: newIndex))
					result.append(.updated(v, at: newIndex))
				}
			}
			return result
		case .reload:
			array = values.sorted(by: compare)
			return [ArrayMutation<Element>(reload: array)]
		}
	}
}

extension SignalInterface {
	func sortedArrayMutation<Element>(equate: @escaping (Element, Element) -> Bool, compare: @escaping (Element, Element) -> Bool) -> Signal<ArrayMutation<Element>> where SetMutation<Element> == OutputValue {
		return transform(initialState: Array<Element>()) { (array: inout Array<Element>, result: Result<SetMutation<Element>>, next: SignalNext<ArrayMutation<Element>>) in
			switch result {
			case .success(let mutation):
				mutation.apply(to: &array, equate: equate, compare: compare).forEach { next.send(value: $0) }
			case .failure(let e): next.send(error: e)
			}
		}
	}
}

// MARK: ### CwlBinderChain.swift ###

/// On its own, `BinderChain` is a description of the connecting structure of `Binder`.
protocol BinderChain: class {
	/// The purpose of a binder is to construct and configure an underlying `Instance`
	associatedtype Instance

	/// Instances are configured with a set of properties and behaviors over time. These are called "bindings"
	associatedtype Binding: BaseBinding where Binding.EnclosingBinder == Self

	/// Bindings are applied to the instance by a helper preparer type. This type exists only during applying of bindings.
	associatedtype Preparer: BinderPreparer where Preparer.EnclosingBinder == Self

	/// Binders inherit from each other with `BaseBinder` usually being the last link in the chain
	associatedtype Inherited

	/// To maintain the lifetime of behaviors over time, binders typically need somewhere to store resources
	associatedtype Storage
}

protocol BaseBinding {
	associatedtype EnclosingBinder
	static func baseBinding(_ binding: BaseBinder.Binding) -> Self
}

/// The primary purpose of the base binder is to terminate the BinderChain but it also includes the `cancelOnClose` binding which can be used for tying lifetimes to the lifetime of the binder's storage.
class BaseBinder: BinderChain {
	typealias Instance = Any
	typealias Storage = Any
	typealias Inherited = ()

	enum Binding: BaseBinding {
		typealias EnclosingBinder = BaseBinder
		static func baseBinding(_ binding: Binding) -> Binding { return binding }

		case cancelOnClose(DynamicValue<[Cancellable]>)
	}

	struct Preparer: BinderPreparer {
		typealias EnclosingBinder = BaseBinder

		init() {}
		var linkedPreparer: () {
			get { return () }
			set { }
		}
		mutating func prepareBinding(_ binding: Binding) {}
		mutating func prepareInstance(_ instance: Instance, storage: Storage) {}
		mutating func finalizeInstance(_ instance: Instance, storage: Storage) -> Cancellable? { return nil }
		func applyBinding(_ binding: Binding, instance: Instance, storage: Storage) -> Cancellable? {
			switch binding {
			case .cancelOnClose(let x):
				switch x {
				case .constant(let array): return ArrayOfCancellables(array)
				case .dynamic(let signal): return signal.continuous().subscribe { r in }
				}
			}
		}
	}
}

extension BindingName where Binding: BaseBinding {
	// You can easily convert the `Binding` cases to `BindingName` using the following Xcode-style regex:
	// Replace: case ([^\(]+)\((.+)\)$
	// With:    static var $1: BindingName<$2, Binding> { return BindingName<$2, Binding>({ v in .baseBinding(BaseBinder.Binding.$1(v)) }) }

	/// Each value in the cancelOnClose will be cancelled when the `Storage` is released. This is guaranteed to be invoked on the main thread (if `Storage` is released on a non-main thread, the effect will occur asynchronously on the main thread).
	static var cancelOnClose: BindingName<DynamicValue<[Cancellable]>, Binding> { return BindingName<DynamicValue<[Cancellable]>, Binding>({ v in .baseBinding(BaseBinder.Binding.cancelOnClose(v)) }) }
}

protocol BinderStorage: class, Cancellable {
	/// The `BinderStorage` needs to maintain the lifetime of all the self-managing objects, the most common of which are `Signal` and `SignalInput` instances but others may include `DispatchSourceTimer`. Most of these objects implement `Cancellable` so maintaining their lifetime is as simple as retaining these `Cancellable` instances in an array.
	/// The `bindings` array should be set precisely once, at the end of construction and an assertion may be raised if subsequent mutations are attempted.
	func setCancellables(_ cancellables: [Cancellable])
	
	/// Since the `BinderStorage` object is a supporting instance for the stateful object and exists to manage interactions but it is possible that the stateful object is constructed without the intention of mutation or interaction – in which case, the `BinderStorage` is not needed. The `inUse` getter is provided to ask if the `BinderStorage` is really necessary (a result of `true` may result in the `BinderStorage` being immediately discarded).
	var inUse: Bool { get }
}

// MARK: ### CwlFilteredAdapter.swift ###

/// Instead of offering a single "notification" output signal, like a plain `StateAdapter`, the `FilteredAdapter` is optimized around the idea of multiple filtered views of the output, with subtle questions like "whether to notify immediately upon connecting" handled by the filtered view, rather than a behavior baked into the adapter.
/// A single shared `State` is shared between the `reducer` and filter stages of the pipeline using a manual synchronization context to ensure this remains threadsafe. The `withMutableState` function offers synchronous, threadsafe access to the same storage for serialization and other concerns that might require immediate access.
/// However, there are also some omissions. Unlike `StateAdapter`, this *requires* an initial `State`. There is also no built-in support for `Codable`, since this `FilteredAdapter` would typically be used on data where serialization and persistence are manually handled.
struct FilteredAdapter<Message, State, Notification>: Cancellable, SignalInputInterface {	
	typealias InputValue = Message
	typealias OutputValue = State
	enum PossibleNotification {
		case never
		case suppress
		case value(Notification)
	}
	
	let pair: SignalMultiPair<Message, PossibleNotification>
	var input: SignalInput<Message> { return pair.input }
	
	private let context: DispatchQueueContext
	private let state: MutableBox<State>
	
	/// Construction where the `reducer` function includes a `loopback` parameter
	///
	/// - Parameters:
	///   - initialState: used to initialize the adapter state
	///   - sync: the adapter's execution context can be synchronous or asychronous but otherwise can't be directly specified (true, by default)
	///   - cacheNotification: the last emitted notification can be cached for new observers (false, by default)
	///   - reducer: the reducing function which combines the internal `State` and `Message` on each iteration, emitting a `Notification?` (or throwing in the case of unrecoverable error or close state). A `loopback` parameter is provided which allows the reducing function to schedule asynchronous tasks that may call back into the adapter at a later time.
	init(initialState: State, sync: Bool = true, cacheNotification: Bool = false, reducer: @escaping (_ state: inout State, _ message: Message, _ loopback: SignalMultiInput<Message>) throws -> Notification?) {
		state = MutableBox<State>(initialState)
		context = DispatchQueueContext(sync: sync)
		let channel = Signal<Message>.multiChannel()
		let loopback = channel.input
		pair = channel.reduce(initialState: .never, context: .custom(context)) { [state, loopback] (cache: inout PossibleNotification, message: Message) -> PossibleNotification in
			let notification = try reducer(&state.value, message, loopback)
			if let n = notification {
				if cacheNotification {
					cache = .value(n)
				}
				return .value(n)
			}
			return .suppress
		}
	}
	
	
	/// Construction where the `reducer` function omits the `loopback` parameter
	///
	/// - Parameters:
	///   - initialState: used to initialize the adapter state
	///   - sync: the adapter's execution context can be synchronous or asychronous but otherwise can't be directly specified (true, by default)
	///   - cacheNotification: the last emitted notification can be cached for new observers (false, by default)
	///   - reducer: the reducing function which combines the internal `State` and `Message` on each iteration, emitting a `Notification?` (or throwing in the case of unrecoverable error or close state).
	init(initialState: State, sync: Bool = true, cacheNotification: Bool = false, reducer: @escaping (_ state: inout State, _ input: Message) throws -> Notification?) {
		self.init(initialState: initialState, sync: sync, cacheNotification: cacheNotification) { (state: inout State, input: Message, collector: SignalMultiInput<Message>) -> Notification? in
			return try reducer(&state, input)
		}
	}
	
	/// Cancels the signal graph (no further actions will be possible).
	func cancel() {
		pair.input.cancel()
	}
	
	/// Filters the `PossibleNotification` output signal down to `Notification`, turning the initial `never` into a value using the provided `initial` function. When `PossibleNotification` is `suppress` (i.e. the last reducer invocation returned `nil`) no notification signal will be emitted.
	///
	/// - Returns: the notificationSignal
	func notificationSignal(initial: @escaping (State) -> Notification? = { _ in nil }) -> Signal<Notification> {
		return pair.signal.compactMap { [state] (possibleNotification: PossibleNotification) in
			switch possibleNotification {
			case .never: return initial(state.value)
			case .suppress: return nil
			case .value(let n): return n
			}
		}
	}
	
	var stateSignal: Signal<State> {
		return pair.signal.compactMap { [state] (possibleNotification: PossibleNotification) -> State? in
			if case .suppress = possibleNotification {
				return nil
			}
			return state.value
		}
	}
	
	/// This is the canonical output of the `FilteredAdapter`. On initial connection and each non-nil returning invocation of the adapter, the `processor` provided to this function is given a chance to produce and emit a slice of the `State` to its listeners.
	///
	/// - initialValue: a context value passed into the processor on each invocation
	/// - processor: the function that produces and emits the slice of `State`. The `State` is provided as an `UnsafePointer`, since Swift doesn't have another way to indicate read-only pass-by-reference. The `Notification?` parameter will be `nil` on initial invocation but will never be `nil` again after that point – this distinction allows construction of a specialized slice on initial connection. Output from the function is via the `SignalNext<Processed>` parameter, allowing zero, one or more value outputs or a close, if desired.
	/// - Returns: the signal output from the `processor`
	func filteredSignal<Value, Processed>(initialValue: Value, _ processor: @escaping (inout Value, State, Notification?, SignalNext<Processed>) throws -> Void) -> Signal<Processed> {
		return pair.signal.transform(initialState: initialValue) { [state] (value: inout Value, incoming: Result<PossibleNotification>, next: SignalNext<Processed>) in
			do {
				switch try incoming.unwrap() {
				case .never: try processor(&value, state.value, nil, next)
				case .suppress: break
				case .value(let n): try processor(&value, state.value, n, next)
				}
			} catch {
				next.send(error: error)
			}
		}
	}
	
	/// Same as `filteredSignal(initialValue:_:)` minus the context value
	///
	/// - processor: the function that produces and emits the slice of `State`. The `State` is provided as an `UnsafePointer`, since Swift doesn't have another way to indicate read-only pass-by-reference. The `Notification?` parameter will be `nil` on initial invocation but will never be `nil` again after that point – this distinction allows construction of a specialized slice on initial connection. Output from the function is via the `SignalNext<Processed>` parameter, allowing zero, one or more value outputs or a close, if desired.
	/// - Returns: the signal output from the `processor`
	func filteredSignal<Processed>(_ processor: @escaping (State, Notification?, SignalNext<Processed>) throws -> Void) -> Signal<Processed> {
		return filteredSignal(initialValue: ()) { (value: inout (), state: State, notification: Notification?, next: SignalNext<Processed>) throws in
			try processor(state, notification, next)
		}
	}
	
	/// Allows out-of-stream access to the `State` (for synchronous actions like save). Since this function acquires the context where the signal closures run, do *not* call this from one of the `filterSignal` or `notificationSignal` processing closures as it will deadlock attempting re-entrant access to the context.
	func withMutableState<Value>(_ perform: (inout State) throws -> Value) rethrows -> Value {
		return try context.queue.sync {
			try perform(&state.value)
		}
	}
}

// MARK: ### CwlObjectStorage.swift ###

/// Implementation for `BinderStorage` that wraps Cocoa objects.
class ObjectBinderStorage: NSObject, BinderStorage {
	fileprivate var cancellables: [Cancellable]? = nil
	func setCancellables(_ cancellables: [Cancellable]) {
		assert(self.cancellables == nil, "Bindings should be set once only")
		self.cancellables = cancellables
	}
	
	// An `ObjectBinderStorage` is an "internal" object but we don't need to keep it around if it isn't in-use. By default, that means: are we using the object for binding or delegation. Subclasses that store additional properties or implement delegate methods directly (without forwarding to the dynamic delegate) must override this with additional logic.
	var inUse: Bool {
		return cancellables?.isEmpty == false || dynamicDelegate != nil
	}
	
	/// Explicitly invoke `cancel` on each of the bindings.
	///
	/// WARNING: if `cancel` is invoked outside the main thread, it will be *asynchronously* invoked on the main thread.
	/// Normally, a `cancel` effect is expected to have synchronous effect but it since `cancel` on EnclosingBinder objects is usually used for breaking reference counted loops, it is considered that the synchronous effect of cancel is less important than avoiding deadlocks – and deadlocks would be easy to accidentally trigger if this were synchronously invoked. If you need synchronous effect, ensure that cancel is invoked on the main thread.
	func cancel() {
		if let cs = cancellables {
			if Thread.isMainThread {
				// `cancel` is mutating so we must use a `for var` (we can't use `forEach`)
				for var c in cs {
					c.cancel()
				}
			} else {
				DispatchQueue.main.sync {
					// `cancel` is mutating so we must use a `for var` (we can't use `forEach`)
					for var c in cs {
						c.cancel()
					}
				}
			}
			cancellables?.removeAll()
		}
	}
	
	deinit {
		cancel()
	}
	
	/// The `dynamicDelegate` is a work-around for the fact that some Cocoa objects change their behavior if you have a delegate that implements a given delegate method. Since Binders will likely implement *all* of their delegate methods, the dynamicDelegate can be used to selectively respond to particular selectors at runtime.
	var dynamicDelegate: DynamicDelegate?
	
	/// An override of the NSObject method so that the dynamicDelegate can work. When the dynamicDelegate states that it can respond to a given selector, that selector is directed to the dynamicDelegate instead. This function will only be involved if Objective-C message sends are sent to the BinderStorage – a rare occurrence outside of deliberate delegate invocations.
	///
	/// - Parameter selector: Objective-C selector that may be implemented by the dynamicDelegate
	/// - Returns: the dynamicDelegate, if it implements the selector
	override func forwardingTarget(for selector: Selector) -> Any? {
		if let dd = dynamicDelegate, dd.implementedSelectors.contains(selector) {
			return dd
		}
		return nil
	}
	
	/// An override of the NSObject method so that the dynamicDelegate can work.
	///
	/// - Parameter selector: Objective-C selector that may be implemented by the dynamicDelegate
	/// - Returns: true if the dynamicDelegate implements the selector, otherwise returns the super implementation
	override func responds(to selector: Selector) -> Bool {
		if let dd = dynamicDelegate, dd.implementedSelectors.contains(selector) {
			return true
		}
		return super.responds(to: selector)
	}
}

/// Used in conjunction with `ObjectBinderStorage`, subclasses of `DynamicDelegate` can implement all delegate methods at compile time but have the `ObjectBinderStorage` report true to `responds(to:)` only in the cases where the delegate method is selected for enabling.
class DynamicDelegate: NSObject, Cancellable {
	var implementedSelectors = Set<Selector>()
	
	@discardableResult
	func addSelector(_ selector: Selector) -> Self {
		implementedSelectors.insert(selector)
		return self
	}
	
	func cancel() {
		implementedSelectors = []
	}
}


/// Most objects managed by a `BinderStorage` are Objective-C objects (`NSView`/`UIView`, `NSApplication`/`UIApplication`, etc). For these objects, we can satisfy the requirement of tying the stateful and binder objects together by storing the binder in the Objective-C "associated object" storage.
private var associatedStorageKey = NSObject()
extension NSObject { 
	func setBinderStorage(_ newValue: BinderStorage?) {
		objc_setAssociatedObject(self, &associatedStorageKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
	}
	func getBinderStorage<T: BinderStorage>(type: T.Type) -> T? {
		return objc_getAssociatedObject(self, &associatedStorageKey) as? T
	}
}

func embedStorageIfInUse<Storage: BinderStorage>(_ instance: NSObject, _ storage: Storage, _ cancellables: [Cancellable]) {
	storage.setCancellables(cancellables)
	if storage.inUse {
		instance.setBinderStorage(storage)
	}
}

// MARK: ### CwlArrayMutationUtilities.swift ###

extension Sequence {
	func arrayMutation() -> ArrayMutation<Element> {
		return .reload(self)
	}
	
	func rowMutation() -> TableRowMutation<Element> {
		return TableRowMutation(arrayMutation: arrayMutation())
	}
	
#if os(iOS)
	func sectionMutation(header: String? = nil, footer: String? = nil) -> TableSectionMutation<Element> {
		return rowMutation().sectionMutation(header: header, footer: footer)
	}
	func tableData(header: String? = nil, footer: String? = nil) -> TableData<Element> {
		return rowMutation().sectionMutation(header: header, footer: footer).tableData()
	}
#endif
}

extension ArrayMutation {
	/// Construct a mutation that represents the insertion of a value at an index.
	static func inserted(_ value: Value, at index: Int) -> ArrayMutation<Value> {
		return ArrayMutation(insertedIndex: index, value: value)
	}

	/// Construct a mutation that discards any previous history and simply starts with a completely new array.
	static func reload<S: Sequence>(_ values: S) -> ArrayMutation<Value> where S.Element == Value {
		return ArrayMutation(reload: Array(values))
	}

	/// Construct a mutation that represents the update of a value at an index.
	static func updated(_ value: Value, at index: Int) -> ArrayMutation<Value> {
		return ArrayMutation(updatedIndex: index, value: value)
	}

	/// Construct a mutation that represents the update of a value at an index.
	static func moved(from sourceIndex: Int, to targetIndex: Int) -> ArrayMutation<Value> {
		return ArrayMutation(movedIndex: sourceIndex, targetIndex: targetIndex)
	}
	
	func rowMutation() -> TableRowMutation<Value> {
		return TableRowMutation(arrayMutation: self)
	}
	
#if os(iOS)
	func sectionMutation(header: String? = nil, footer: String? = nil) -> TableSectionMutation<Value> {
		return rowMutation().sectionMutation(header: header, footer: footer)
	}
	
	func tableData(header: String? = nil, footer: String? = nil) -> TableData<Value> {
		return rowMutation().sectionMutation(header: header, footer: footer).tableData()
	}
#endif
}

#if os(iOS)
extension TableRowMutation {
	func sectionMutation(header: String? = nil, footer: String? = nil) -> TableSectionMutation<Value> {
		return TableSectionMutation(header: header, footer: footer, rowMutation: self)
	}
	
	func tableData(header: String? = nil, footer: String? = nil) -> TableData<Value> {
		return sectionMutation(header: header, footer: footer).tableData()
	}
}

extension TableSectionMutation {
	func tableData() -> TableRowMutation<TableSectionMutation<Value>> {
		return TableRowMutation(array: [self])
	}
}

extension TableRowMutation {
	static func tableData<RowData>(sections: [TableSectionMutation<RowData>]) -> TableData<RowData> where TableSectionMutation<RowData> == Value {
		return TableRowMutation(array: sections)
	}

	static func tableDataFromSections<RowData>(_ sections: TableSectionMutation<RowData>...) -> TableData<RowData> where TableSectionMutation<RowData> == Value {
		return TableRowMutation(array: sections)
	}
}
#endif

extension SignalInterface {
	func arrayMutationToRowMutation<Value>() -> Signal<TableRowMutation<Value>> where ArrayMutation<Value> == OutputValue {
		return map(initialState: 0) { (globalCount: inout Int, arrayMutation: ArrayMutation<Value>) -> TableRowMutation<Value> in
			arrayMutation.delta(&globalCount)
			return TableRowMutation(arrayMutation: arrayMutation, localOffset: 0, globalCount: globalCount)
		}
	}
	
#if os(iOS)
	func arrayMutationToSectionMutation<Value>(header: String? = nil, footer: String? = nil) -> Signal<TableSectionMutation<Value>> where ArrayMutation<Value> == OutputValue {
		return map(initialState: 0) { (globalCount: inout Int, arrayMutation: ArrayMutation<Value>) -> TableSectionMutation<Value> in
			arrayMutation.delta(&globalCount)
			return TableSectionMutation(header: header, footer: footer, rowMutation: TableRowMutation(arrayMutation: arrayMutation, localOffset: 0, globalCount: globalCount))
		}
	}

	func tableData<Value>() -> Signal<TableData<Value>> where ArrayMutation<Value> == OutputValue {
		return Signal.sections(Signal.section(rowSignal: signal.map(initialState: 0) { (globalCount: inout Int, arrayMutation: ArrayMutation<Value>) -> TableRowMutation<Value> in
				arrayMutation.delta(&globalCount)
				return TableRowMutation(arrayMutation: arrayMutation, localOffset: 0, globalCount: globalCount)
			})
		)
	}
	
	static func sections<RowData>(signals: [Signal<TableSectionMutation<RowData>>]) -> Signal<TableRowMutation<TableSectionMutation<RowData>>> where TableRowMutation<TableSectionMutation<RowData>> == OutputValue {
		var result: [Signal<TableRowMutation<TableSectionMutation<RowData>>>] = []
		let count = signals.count
		for (index, sectionSignal) in signals.enumerated() {
			result += sectionSignal.map { section in
				let mutation = ArrayMutation<TableSectionMutation<RowData>>(updatedIndex: index, value: section)
				return TableRowMutation(arrayMutation: mutation, localOffset: 0, globalCount: count, animation: noTableViewAnimation)
			}
		}
		let sections = TableRowMutation<TableSectionMutation<RowData>>(arrayMutation: ArrayMutation(insertedRange: 0..<signals.count, values: Array<TableSectionMutation<RowData>>(repeating: TableSectionMutation<RowData>(), count: signals.count)), localOffset: 0, globalCount: signals.count)
		let (mergedInput, mergedSignal) = Signal<TableRowMutation<TableSectionMutation<RowData>>>.createMergedInput()
		for s in result {
			mergedInput.add(s)
		}
		return mergedSignal.startWith([sections])
	}

	static func sections<RowData>(_ signals: Signal<TableSectionMutation<RowData>>...) -> Signal<TableRowMutation<TableSectionMutation<RowData>>> where TableRowMutation<TableSectionMutation<RowData>> == OutputValue {
		return sections(signals: signals)
	}

	static func section<Value>(header: String? = nil, footer: String? = nil, rowSignal: Signal<TableRowMutation<Value>>) -> Signal<OutputValue> where TableSectionMutation<Value> == OutputValue {
		return rowSignal.map(initialState: false) { (state: inout Bool, value: TableRowMutation<Value>) -> TableSectionMutation<Value> in
			if !state {
				state = true
				return TableSectionMutation<Value>(header: header, footer: footer, rowMutation: value)
			} else {
				return TableSectionMutation<Value>(rowMutation: value)
			}
		}
	}
#endif
}

// MARK: ### CwlCoder.swift ###

import Foundation

extension NSCoder {
	/// Gets the latest value from the signal and encodes the value as JSON data into self using the provided key
	///
	/// - Parameters:
	///   - interface: exposes the signal
	///   - forKey: key used for encoding (is `String.viewStateKey` by default)
	func encodeLatest<Interface>(from interface: Interface, forKey: String = .viewStateKey) where Interface: SignalInterface, Interface.OutputValue: Codable {
		if let data = interface.peekData() {
			_ = self.encode(data, forKey: forKey)
		}
	}

	/// Decodes the JSON data in self, associated with the provided key, and sends into the signal input.
	///
	/// - Parameters:
	///   - inputInterface: exposes the signal input
	///   - forKey: key used for decoding (is `String.viewStateKey` by default)
	func decodeSend<InputInterface>(to inputInterface: InputInterface, forKey: String = .viewStateKey) where InputInterface: SignalInputInterface, InputInterface.InputValue: Codable {
		if let data = self.decodeObject(forKey: forKey) as? Data, let value = try? JSONDecoder().decode(InputInterface.InputValue.self, from: data) {
			inputInterface.input.send(value: value)
		}
	}
}

extension SignalInterface where OutputValue == Data {
	func decode<Target: Decodable>(as decodableType: Target.Type) -> Signal<Target> {
		return transformValues { v, n in n.send(value: try! JSONDecoder().decode(decodableType, from: v)) }
	}
}

extension SignalInterface where OutputValue: Encodable {
	func peekData() -> Data? {
		return peek().flatMap { try? JSONEncoder().encode($0) }
	}

	func data() -> Signal<Data> {
		return transformValues { v, n in n.send(value: try! JSONEncoder().encode(v)) }
	}

	/// This function subscribes to the signal and logs emitted values as JSON data to the console
	///
	/// - Parameter prefix: pre-pended to each JSON value
	/// - Returns: an endpoint which will keep this logger alive
	func logJson(prefix: String = "", outputFormatting: JSONEncoder.OutputFormatting = .prettyPrinted) -> SignalEndpoint<OutputValue> {
		return subscribe { result in
			switch result {
			case .success(let v):
				let enc = JSONEncoder()
				enc.outputFormatting = outputFormatting
				if let data = try? enc.encode(v), let string = String(data: data, encoding: .utf8) {
					print("\(prefix)\(string)")
				}
			case .failure(let e):
				print("\(prefix)\(e)")
			}
		}
	}
}

extension String {
	static let viewStateKey = "viewStateData"
}

// MARK: ### CwlStateAdapter.swift ###

struct NonPersistentStateAdapterState: Codable, Error {}

protocol StateAdapterBehavior {
	associatedtype State
	associatedtype Message
	associatedtype Notification
	associatedtype PersistentState: Codable = NonPersistentStateAdapterState
	
	static func reducer(state: inout State, message: Message) -> Notification?
	static func resume(state: State) -> Notification?
	static func initialize(message: Message) -> (State?, Notification?)
	static func persistentState(_ state: State) -> PersistentState
	static func stateFromPersistentState(_ state: PersistentState) throws -> State
	static func stateAsStateContainer(_ state: State) -> StateContainer?
	static var stateIsStateContainer: Bool { get }
}

// These extensions are a workaround to the fact that we can't dynamically query conditional conformances yet in Swift 4.1 beta
extension StateAdapterBehavior {
	static var stateIsStateContainer: Bool { return false }
	static func stateAsStateContainer(_ state: State) -> StateContainer? { return nil }
}

// These extensions are a workaround to the fact that we can't dynamically query conditional conformances yet in Swift 4.1 beta
extension StateAdapterBehavior where State: StateContainer {
	static var stateIsStateContainer: Bool { return true }
	static func stateAsStateContainer(_ state: State) -> StateContainer? { return state }
}

extension StateAdapterBehavior where PersistentState == NonPersistentStateAdapterState {
	static func childValues(_ state: State) -> [StateContainer]? {
		return nil
	}
	
	static func persistentState(_ state: State) -> PersistentState {
		return NonPersistentStateAdapterState()
	}
	
	static func stateFromPersistentState(_ state: PersistentState) throws -> State {
		throw NonPersistentStateAdapterState()
	}
}

extension StateAdapterBehavior where PersistentState == State {
	static func persistentState(_ state: State) -> PersistentState {
		return state
	}
	
	static func stateFromPersistentState(_ state: PersistentState) throws -> State {
		return state
	}
}

struct StateAdapter<RB: StateAdapterBehavior>: StateContainer, SignalInputInterface, SignalInterface {
	typealias OutputValue = RB.Notification
	typealias InputValue = RB.Message
	
	private enum Content {
		case none
		case state(RB.State)
		case notification(RB.State?, RB.Notification?)
	}
	
	private let channel: SignalChannel<RB.Message, SignalMultiInput<RB.Message>, Content, SignalMulti<Content>>
	
	var input: SignalInput<RB.Message> { return channel.input }
	var signal: Signal<RB.Notification> { return channel.signal.compactMap {
		switch $0 {
		case .none: return nil
		case .state(let s): return RB.resume(state: s)
		case .notification(_, let n): return n
		}
	} }
	
	private init(initialState: Content) {
		channel = Signal<RB.Message>.multiChannel().reduce(initialState: initialState) { (content: inout Content, message: RB.Message) -> Content in
			switch content {
			case .none, .notification(.none, _):
				let (possibleState, notification) = RB.initialize(message: message)
				if let state = possibleState {
					content = Content.state(state)
				}
				return Content.notification(possibleState, notification)
			case .state(var s):
				let n = RB.reducer(state: &s, message: message)
				content = Content.state(s)
				return Content.notification(s, n)
			case .notification(.some(var s), _):
				let n = RB.reducer(state: &s, message: message)
				content = Content.state(s)
				return Content.notification(s, n)
			}
		}
	}
	
	init(_ initialValue: RB.State) {
		self.init(initialState: Content.state(initialValue))
	}
	
	init() {
		self.init(initialState: Content.none)
	}
	
	func cancel() {
		if RB.stateIsStateContainer, let value = stateSignal.peek(), let sc = RB.stateAsStateContainer(value) {
			sc.cancel()
		}
		input.cancel()
	}
	
	var childValues: [StateContainer] {
		if RB.stateIsStateContainer, let value = stateSignal.peek(), let sc = RB.stateAsStateContainer(value) {
			return sc.childValues
		}
		return []
	}

	var stateSignal: Signal<RB.State> {
		return channel.signal.compactMap { (content: Content) -> RB.State? in
			switch content {
			case .none, .notification(nil, _): return nil
			case .state(let s): return s
			case .notification(.some(let s), _): return s
			}
		}
	}
	
	var persistentValueChanged: Signal<()> {
		if RB.PersistentState.self == NonPersistentStateAdapterState.self {
			return Signal<()>.preclosed()
		}
		
		if !RB.stateIsStateContainer {
			return stateSignal.map { _ in () }.dropActivation()
		}
		
		return channel.signal.flatMapLatest { (content: Content) -> Signal<()> in
			switch content {
			case .state(let s):
				return RB.stateAsStateContainer(s)?.persistentValueChanged ?? Signal<()>.preclosed()
			case .notification(let s as StateContainer, _):
				return s.persistentValueChanged.startWith(())
			default: return Signal<()>.preclosed()
			}
		}.dropActivation()
	}
	
	enum Keys: CodingKey { case `var` }
	
	func encode(to encoder: Encoder) throws {
		if RB.PersistentState.self != NonPersistentStateAdapterState.self, let s = stateSignal.peek() {
			var c = encoder.container(keyedBy: Keys.self)
			try c.encode(RB.persistentState(s), forKey: .var)
		}
	}
	
	init(from decoder: Decoder) throws {
		if RB.PersistentState.self == NonPersistentStateAdapterState.self {
			self.init()
			return
		}
		
		// Decoding must:
		// * Use keyed container
		// * Call `decode`, not `decodeIfPresent`
		// * Catch errors from the `decode` (using try? and optional unwrapping is insufficient)
		// Unless I've missed something, this specific pattern appears to be necessary to correctly decode potentially optional `RB.PersistentState` without *knowing* whether it is defined as an optional – but also handle a situation where it might not be present at all.
		let c = try decoder.container(keyedBy: Keys.self)
		let state = try c.decode(RB.PersistentState.self, forKey: .var)
		try self.init(RB.stateFromPersistentState(state))
	}
}

enum VarChange<Value> {
	case set(Value)
	case update(Value)
	case notify(Value)
}

struct VarBehavior<Value: Codable>: StateAdapterBehavior {
	typealias State = Value
	typealias Message = VarChange<Value>
	typealias Notification = Value
	typealias PersistentState = Value
	
	static func reducer(state: inout State, message: Message) -> Notification? {
		switch message {
		case .set(let v):
			state = v
			return v
		case .update(let v):
			state = v
			return nil
		case .notify(let v):
			return v
		}
	}
	
	static func resume(state: State) -> Notification? {
		return state
	}
	
	static func initialize(message: Message) -> (Value?, Value?) {
		switch message {
		case .set(let v): return (v, v)
		case .update(let v): return (v, nil)
		case .notify(let v): return (nil, v)
		}
	}
}

struct Var<Value: Codable>: StateContainer, SignalInputInterface, SignalInterface {
	typealias OutputValue = Value
	typealias InputValue = Value

	let adapter: StateAdapter<VarBehavior<Value>>
	
	var input: SignalInput<Value> { return Input().map { .set($0) }.bind(to: adapter.input) }
	var signal: Signal<Value> { return adapter.signal }

	init(_ initialValue: Value) {
		adapter = StateAdapter(initialValue)
	}
	var updatingInput: SignalInput<Value> {
		return Input().map { .update($0) }.bind(to: adapter.input)
	}
	
	var notifyingInput: SignalInput<Value> {
		return Input().map { .notify($0) }.bind(to: adapter.input)
	}

	func saveToCoder(_ coder: NSCoder) {
		coder.encodeLatest(from: adapter.stateSignal)
	}
	
	func restoreFromCoder(_ coder: NSCoder) {
		coder.decodeSend(to: input)
	}
	
	var persistentValueChanged: Signal<()> {
		return adapter.persistentValueChanged
	}
	
	func logJson(prefix: String = "") -> SignalEndpoint<Var<Value>> {
		return persistentValueChanged.map { _ in
			self
		}.startWith(self).logJson(prefix: prefix)
	}
	
	var childValues: [StateContainer] {
		return adapter.childValues
	}

	func encode(to encoder: Encoder) throws {
		var c = encoder.singleValueContainer()
		try c.encode(adapter)
	}
	
	init(from decoder: Decoder) throws {
		let c = try decoder.singleValueContainer()
		self.adapter = try c.decode(StateAdapter<VarBehavior<Value>>.self)
	}
}

struct TempBehavior<Value>: StateAdapterBehavior {
	typealias State = Value
	typealias Message = Value
	typealias Notification = Value
	
	static func reducer(state: inout State, message: Message) -> Notification? {
		state = message
		return state
	}
	
	static func resume(state: State) -> Notification? {
		return state
	}
	
	static func initialize(message: Message) -> (Value?, Value?) {
		return (message, message)
	}
}

typealias TempVar<Value> = StateAdapter<TempBehavior<Value>>

struct ToggleBehavior: StateAdapterBehavior {
	typealias State = Bool
	typealias Message = ()
	typealias Notification = Bool
	typealias PersistentState = Bool
	
	static func reducer(state: inout State, message: Message) -> Notification? {
		state = !state
		return state
	}
	
	static func resume(state: State) -> Notification? {
		return state
	}
	
	static func initialize(message: Message) -> (State?, State?) {
		return (false, false)
	}
}

typealias ToggleAdapter = StateAdapter<ToggleBehavior>

// MARK: ### CwlBinderPreparer.swift ###

/// A preparer interprets a set of bindings and applies them to an instance.
protocol BinderPreparer {
	associatedtype EnclosingBinder: BinderChain

	// A preparer must be default constructible (the bindings are the parameters)
	init()
	
	/// A first scan of the bindings. Information about bindings present may be recorded during this time.
	///
	/// - Parameter binding: the binding to apply
	mutating func prepareBinding(_ binding: EnclosingBinder.Binding)
	
	/// Bindings which need to be applied before others can be applied at this special early stage
	///
	/// - Parameters:
	///   - instance: the instance
	///   - storage: the storage
	mutating func prepareInstance(_ instance: EnclosingBinder.Instance, storage: EnclosingBinder.Storage)
	
	/// Apply typical bindings.
	///
	/// - Parameters:
	///   - binding: the binding to apply
	///   - instance: the instance
	///   - storage: the storage
	/// - Returns: If maintaining bindings requires ongoing lifetime management, these lifetimes are maintained by returning instances of `Cancellable`.
	func applyBinding(_ binding: EnclosingBinder.Binding, instance: EnclosingBinder.Instance, storage: EnclosingBinder.Storage) -> Cancellable?
	
	/// Bindings which need to be applied after others can be applied at this last stage.
	///
	/// - Parameters:
	///   - instance: the instance
	///   - storage: the storage
	/// - Returns: If maintaining bindings requires ongoing lifetime management, these lifetimes are maintained by returning instances of `Cancellable`
	mutating func finalizeInstance(_ instance: EnclosingBinder.Instance, storage: EnclosingBinder.Storage) -> Cancellable?
}

/// Preparers are normally linked together in a chain, mimicking the chain of Binders, so Bindings from the linked Binder can be applied to current instance.
protocol DerivedPreparer: BinderPreparer where EnclosingBinder: Binder {
	/// Inherited bindings will be applied by the inherited preparer
	var linkedPreparer: EnclosingBinder.Inherited.Preparer { get set }
}

/// Preparers usually default construct the `Storage` except in specific cases where the storage needs a reference to the instance.
protocol StoragePreparer: DerivedPreparer {
	/// Constructs the `Storage`
	///
	/// - Returns: the storage
	func constructStorage() -> EnclosingBinder.Storage
}

/// Preparers usually construct the `Instance` from a subclass type except in specific cases where additional non-binding parameters are required for instance construction.
protocol ConstructingPreparer: StoragePreparer {
	/// Constructs the `Instance`
	///
	/// - Parameter subclass: subclass of the instance type to use for construction
	/// - Returns: the instance
	func constructInstance(subclass: EnclosingBinder.Instance.Type) -> EnclosingBinder.Instance
}

extension DerivedPreparer {
	/// Invokes `prepareBinding` once with each element of the `bindings`
	///
	/// - Parameter bindings: prepareBinding will be invoked with each element
	mutating func prepareBindings( _ bindings: [EnclosingBinder.Binding]) {
		for b in bindings {
			prepareBinding(b)
		}
	}
	
	/// The default prepare workflow – in either `Binder.binderConstruct` or `Binder.binderApply` is, in order: `prepareBindings` (`constructInstance` for `Binder.binderConstruct`), `constructStorage` and then this function.
	///
	/// - Parameters:
	///   - bindings: from the binder parameters
	///   - instance: the constructed or apply instance
	///   - storage: the constructed storage
	///   - additional: any ad hoc bindings
	///   - combine: link the instance, storage and cancellables together
	mutating func applyBindings(_ bindings: [EnclosingBinder.Binding], instance: EnclosingBinder.Instance, storage: EnclosingBinder.Storage, additional: ((EnclosingBinder.Instance) -> Cancellable?)?, combine: (EnclosingBinder.Instance, EnclosingBinder.Storage, [Cancellable]) -> ()) {
		// Prepare.
		prepareInstance(instance, storage: storage)
		
		// Apply styles that need to be applied after construction
		var cancellables = [Cancellable]()
		for b in bindings {
			if let c = applyBinding(b, instance: instance, storage: storage) {
				cancellables.append(c)
			}
		}
		
		// Finalize the instance
		if let c = finalizeInstance(instance, storage: storage) {
			cancellables.append(c)
		}
		
		// Append adhoc bindings, if any
		if let a = additional, let c = a(instance) {
			cancellables.append(c)
		}
		
		// Combine the instance and binder
		combine(instance, storage, cancellables)
	}

	/// A first scan of the bindings. Information about bindings present may be recorded during this time.
	///
	/// - Parameter binding: the binding to apply
	mutating func prepareBinding(_ binding: EnclosingBinder.Binding) {
		if let ls = EnclosingBinder.bindingToInherited(binding) {
			linkedPreparer.prepareBinding(ls)
		}
	}
	
	/// Bindings which need to be applied before others can be applied at this special early stage
	///
	/// - Parameters:
	///   - instance: the instance
	///   - storage: the storage
	mutating func prepareInstance(_ instance: EnclosingBinder.Instance, storage: EnclosingBinder.Storage) {
		if let i = instance as? EnclosingBinder.Inherited.Instance, let s = storage as? EnclosingBinder.Inherited.Storage {
			linkedPreparer.prepareInstance(i, storage: s)
		}
	}

	/// Apply typical bindings.
	///
	/// - Parameters:
	///   - binding: the binding to apply
	///   - instance: the instance
	///   - storage: the storage
	/// - Returns: If maintaining bindings requires ongoing lifetime management, these lifetimes are maintained by returning instances of `Cancellable`.
	func applyBinding(_ binding: EnclosingBinder.Binding, instance: EnclosingBinder.Instance, storage: EnclosingBinder.Storage) -> Cancellable? {
		if let ls = EnclosingBinder.bindingToInherited(binding), let i = instance as? EnclosingBinder.Inherited.Instance, let s = storage as? EnclosingBinder.Inherited.Storage {
			return linkedPreparer.applyBinding(ls, instance: i, storage: s)
		}
		return nil
	}
	
	/// Bindings which need to be applied after others can be applied at this last stage.
	///
	/// - Parameters:
	///   - instance: the instance
	///   - storage: the storage
	/// - Returns: If maintaining bindings requires ongoing lifetime management, these lifetimes are maintained by returning instances of `Cancellable`
	mutating func finalizeInstance(_ instance: EnclosingBinder.Instance, storage: EnclosingBinder.Storage) -> Cancellable? {
		if let i = instance as? EnclosingBinder.Inherited.Instance, let s = storage as? EnclosingBinder.Inherited.Storage {
			return linkedPreparer.finalizeInstance(i, storage: s)
		}
		return nil
	}
}

// MARK: ### CwlDynamicValue.swift ###

/// A simple wrapper around a value used to identify "static" bindings (bindings which are applied only at construction time)
struct StaticValue<Value> {
	typealias ValueType = Value
	let value: Value
	init(_ value: Value) {
		self.value = value
	}
	static func fromConstant(_ value: Value) -> StaticValue<Value> {
		return StaticValue<Value>(value)
	}
}

/// An either type for a value or a signal emitting values of that type. Used for "value" bindings (bindings which set a property on the underlying instance)
enum DynamicValue<Value> {
	typealias ValueType = Value
	case constant(Value)
	case dynamic(Signal<Value>)
	
	static func fromConstant(_ value: Value) -> DynamicValue<Value> {
		return DynamicValue<Value>.constant(value)
	}
	static func fromDynamic(_ value: Signal<Value>) -> DynamicValue<Value> {
		return DynamicValue<Value>.dynamic(value)
	}

	/// Gets the initial (i.e. used in the constructor) value from the `DynamicValue`
	func initialSubsequent() -> InitialSubsequent<Value> {
		switch self {
		case .constant(let v):
			return InitialSubsequent<Value>(initial: v)
		case .dynamic(let signal):
			let sc = signal.capture()
			return InitialSubsequent<Value>(initial: sc.currentValue, subsequent: sc)
		}
	}
	
	/// Gets the initial (i.e. used in the constructor) value from the `DynamicValue`
	func captureValues() -> [Value] {
		switch self {
		case .constant(let v): return [v]
		case .dynamic(let signal): return signal.capture().values
		}
	}
	
	/// Converts this `DynamicValue` into a signal by returning the `.dynamic` signal or returning the `.constant` wrapped in a signal.
	func signal() -> Signal<Value> {
		switch self {
		case .constant(let v): return Signal<Value>.preclosed(v)
		case .dynamic(let signal): return signal
		}
	}
	
	// Gets the subsequent (i.e. after construction) values from the `DynamicValue`
	func apply<I: AnyObject, B: BinderStorage>(_ instance: I, _ storage: B, _ onError: Value? = nil, handler: @escaping (I, B, Value) -> Void) -> Cancellable? {
		switch self {
		case .constant(let v):
			handler(instance, storage, v)
			return nil
		case .dynamic(let signal):
			return signal.subscribe(context: .main) { [weak instance, weak storage] r in
				guard let i = instance, let s = storage else { return }
				switch (r, onError) {
				case (.success(let v), _): handler(i, s, v)
				case (.failure, .some(let v)): handler(i, s, v)
				case (.failure, .none): break
				}
			}
		}
	}
}

struct InitialSubsequent<Value> {
	private var capturedValue: Value?
	var shouldResend: Bool
	let subsequent: SignalCapture<Value>?
	
	init(initial: Value? = nil, shouldResend: Bool = true, subsequent: SignalCapture<Value>? = nil) {
		self.capturedValue = initial
		self.shouldResend = shouldResend
		self.subsequent = subsequent
	}
	
	mutating func initial() -> Value? {
		let c = capturedValue
		capturedValue = nil
		shouldResend = false
		return c
	}

	func resume() -> Signal<Value>? {
		if let s = subsequent {
			return s.resume(resend: shouldResend)
		} else if shouldResend, let i = capturedValue {
			return Signal<Value>.preclosed(i)
		}
		return nil
	}
}

extension Signal {
	func apply<I: AnyObject, B: BinderStorage>(_ instance: I?, _ storage: B?, handler: @escaping (I, B, OutputValue) -> Void) -> Cancellable? {
		return subscribeValues(context: .main) { [weak instance, weak storage] v in
			guard let i = instance, let s = storage else { return }
			handler(i, s, v)
		}
	}
}

extension SignalCapture {
	func apply<I: AnyObject, B: BinderStorage>(_ instance: I, _ storage: B, handler: @escaping (I, B, OutputValue) -> Void) -> Cancellable? {
		return subscribeValues(context: .main) { [weak instance, weak storage] v in
			guard let i = instance, let s = storage else { return }
			handler(i, s, v)
		}
	}
}

extension SignalInterface {
	func adhocBinding<Subclass: AnyObject>(toType: Subclass.Type, using: @escaping (Subclass, OutputValue) -> Void) -> (AnyObject) -> Cancellable? {
		return { (instance: AnyObject) -> Cancellable? in
			return self.signal.subscribeValues(context: .main) { [weak instance] value in
				if let i = instance as? Subclass {
					using(i, value)
				}
			}
		}
	}
}

// MARK: ### CwlStackAdapter.swift ###

import Foundation

/// An "Either" type for use in scenarios where "Equatable" and "Codable" are required but there's only ever a single "Master" instance so equality is implied. This is common in Navigation Controller stacks and Split Views.
enum MasterOrDetail<Master: StateContainer, Detail: StateContainer>: StateContainer {
	case master(Master)
	case detail(Detail)
	
	var childValues: [StateContainer] {
		switch self {
		case .master(let tvm): return [tvm]
		case .detail(let dvm): return [dvm]
		}
	}

	enum Keys: CodingKey { case master, detail }
	
	func encode(to encoder: Encoder) throws {
		var c = encoder.container(keyedBy: Keys.self)
		switch self {
		case .master(let tvm): try c.encode(tvm, forKey: .master)
		case .detail(let dvm): try c.encode(dvm, forKey: .detail)
		}
	}
	
	init(from decoder: Decoder) throws {
		let c = try decoder.container(keyedBy: Keys.self)
		if let tvm = try c.decodeIfPresent(Master.self, forKey: .master) {
			self = .master(tvm)
		} else {
			self = .detail(try c.decode(Detail.self, forKey: .detail))
		}
	}
}

/// This "StateAdapter" is a `ModelSignalValue` that manages a stack of navigation items as might be used by a UINavigationController. The adapter converts `push`, `popToCount` and `reload` messages into updates to the array of `PathElement`. The adapter includes convenient input signals, animated output signals and includes automatic implementation of coding and notification protocols.
struct StackAdapterBehavior<PathElement: Codable>: StateAdapterBehavior {
	typealias State = [PathElement]
	typealias Message = StackMutation<PathElement>
	typealias Notification = StackMutation<PathElement>
	typealias PersistentState = State
	
	static func reducer(state: inout State, message: Message) -> Notification? {
		switch message {
		case .push(let e):
			state.append(e)
			return message
		case .pop:
			_ = state.popLast()
			return message
		case .popToCount(let i):
			if i >= 1, i < state.count {
				state.removeLast(state.count - i)
				return message
			}
			return nil
		case .reload(let newStack):
			state = newStack
			return message
		}
	}
	
	static func resume(state: State) -> Notification? {
		return .reload(state)
	}
	
	static func initialize(message: Message) -> (State?, Notification?) {
		var state = [PathElement]()
		let n = reducer(state: &state, message: message)
		return (state, n)
	}
}

extension StateAdapter where RB.State: Collection, RB.Message == StackMutation<RB.State.Element> {
	var pushInput: SignalInput<RB.State.Element> {
		return Signal<RB.State.Element>.channel().map { RB.Message.push($0) }.bind(to: input)
	}

	var poppedToCount: SignalInput<Int> {
		return Signal<Int>.channel().map { RB.Message.popToCount($0) }.bind(to: input)
	}
}

typealias StackAdapter<PathElement: Codable> = StateAdapter<StackAdapterBehavior<PathElement>>

// MARK: ### CwlConstructingBinder.swift ###

/// A constructing binder can build the instance. As a simplification, this protocol requires that the `Output` and `Instance` types are the same (binders where this is not the case must be built on `Binder`).
protocol ConstructingBinder: Binder where Output == Instance {
	/// Build the instance from the parameters in the binder state or return an already constructed instance. If state is `.consumed` this will trigger a fatal error.
	///
	/// - Parameter additional: ad hoc bindings (this is a chance to apply changes to the instance after construction and establish additional behaviors).
	/// - Returns: the constructed and configured instance (newly created if state was `.pending` or pre-existing if state was `.constructed`)
	func instance(additional: ((Instance) -> Cancellable?)?) -> Instance
}

extension ConstructingBinder where Parameters == BinderSubclassParameters<Instance, Binding>, Preparer: ConstructingPreparer, Instance: NSObject {
	/// Build the instance from the parameters in the binder state or return an already constructed instance. If state is `.consumed` this will trigger a fatal error.
	///
	/// - Parameter additional: ad hoc bindings (this is a chance to apply changes to the instance after construction and establish additional behaviors).
	/// - Returns: the constructed and configured instance (newly created if state was `.pending` or pre-existing if state was `.constructed`)
	func instance(additional: ((Instance) -> Cancellable?)? = nil) -> Instance {
		return binderConstruct(
			additional: additional,
			storageConstructor: { prep, params, i in prep.constructStorage() },
			instanceConstructor: { prep, params in prep.constructInstance(subclass: params.subclass) },
			combine: embedStorageIfInUse,
			output: { i, s in i })
	}
}

